package com.cscj.android.repository.repo.history

import android.graphics.Bitmap
import com.cscj.android.repository.db.dao.BrowserHistoryDao
import com.cscj.android.repository.db.entity.BrowseHistoryEntity
import com.cscj.android.utils.BitmapUtils.asBase64String
import kotlinx.coroutines.flow.Flow
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject

class BrowserHistoryRepositoryImpl : BrowserHistoryRepository, KoinComponent {

    private val browserHistoryDao by inject<BrowserHistoryDao>()

    override suspend fun init() {
        browserHistoryDao.addBrowserHistory(
            BrowseHistoryEntity(
                id = BrowseHistoryEntity.RootId, title = "历史", url = "历史"
            )
        )
    }

    override suspend fun addBrowserHistory(title: String, url: String, favicon: Bitmap?) {
        browserHistoryDao.addBrowserHistory(
            BrowseHistoryEntity(
                title = title, url = url, icon = favicon?.asBase64String()
            )
        )
    }

    override fun browserHistoryList(keyword: String?): Flow<List<BrowseHistoryEntity>> {
        return if (keyword.isNullOrBlank()) {
            browserHistoryDao.browserHistoryList()
        } else {
            browserHistoryDao.browserHistoryList("%$keyword%")
        }
    }

    override fun allBrowserHistory(): Flow<List<BrowseHistoryEntity>> {
        return browserHistoryDao.allHistoryList()
    }

    override suspend fun deleteByIds(ids: IntArray) {
        return browserHistoryDao.deleteByIds(ids)
    }

    override suspend fun clearAllHistory() {
        browserHistoryDao.deleteAll()
    }

    override suspend fun updateFavicon(url: String, favicon: Bitmap?) {
        browserHistoryDao.updateFavicon(url, favicon?.asBase64String())
    }
}